using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 跟随第三人称角色的相机控制脚本
/// 挂载到相机对象上，通过设置target实现跟随角色
/// </summary>
public class CameraMove : MonoBehaviour
{
    [Header("跟随目标")]
    public Transform target; // 角色的Transform

    [Header("相机偏移")]
    public Vector3 offset = new Vector3(0, 5, -8); // 相机与角色的偏移

    [Header("平滑跟随速度")]
    public float smoothSpeed = 0.125f; // 跟随平滑度

    [Header("鼠标视角调整")]
    public float mouseSensitivity = 100f; // 鼠标灵敏度
    private float pitch = 0f; // 上下旋转角度
    private float yaw = 0f; // 左右旋转角度

    private Vector3 velocity = Vector3.zero; // 用于存储平滑移动的速度
    private Vector3 lookAtVelocity = Vector3.zero; // 用于存储注视点的平滑速度
    private Vector3 smoothedLookAtPosition; // 平滑后的注视点位置

    /// <summary>
    /// 在所有Update执行完后调用，保证角色移动后相机再跟随
    /// </summary>
    void LateUpdate()
    {
        if (target == null) return; // 如果没有设置目标则直接返回

        // 检测鼠标右键是否按下
        if (Input.GetMouseButton(1)) // 鼠标右键
        {
            // 获取鼠标移动量
            float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
            float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

            // 调整视角
            yaw += mouseX;
            pitch -= mouseY;
            pitch = Mathf.Clamp(pitch, -45f, 45f); // 限制上下旋转角度
        }

        // 计算旋转后的偏移
        Quaternion rotation = Quaternion.Euler(pitch, yaw, 0);
        Vector3 rotatedOffset = rotation * offset;

        // 计算理想位置
        Vector3 desiredPosition = target.position + rotatedOffset;

        // 使用SmoothDamp实现平滑移动，减少抖动
        Vector3 smoothedPosition = Vector3.SmoothDamp(transform.position, desiredPosition, ref velocity, smoothSpeed);

        // 设置相机位置
        transform.position = smoothedPosition;

        // 平滑注视点，减少抖动
        Vector3 desiredLookAtPosition = target.position + Vector3.up * offset.y;
        smoothedLookAtPosition = Vector3.SmoothDamp(smoothedLookAtPosition, desiredLookAtPosition, ref lookAtVelocity, smoothSpeed);

        // 让相机始终看向平滑后的注视点
        transform.LookAt(smoothedLookAtPosition);
    }
}
